import datetime

from django.db import models
from django.db.models import Max

from base.models import Goods, StoreHouse, CustomSupplier
from users.models import UserInfo


class GoodsStock(models.Model):
    """商品库存"""
    goods = models.ForeignKey(to=Goods, verbose_name='商品名称', related_name="stocks", blank=True, null=True, on_delete=models.CASCADE, db_constraint=False)
    house = models.ForeignKey(to=StoreHouse, verbose_name='所属仓库', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    batch_num = models.CharField(verbose_name='批号', max_length=16, blank=True, null=True)
    supplier = models.ForeignKey(to=CustomSupplier, verbose_name='供应商', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    specs = models.CharField(verbose_name='规格', max_length=32, blank=True, null=True)
    brand = models.CharField(verbose_name='品牌', max_length=32, blank=True, null=True)
    place = models.CharField(verbose_name='产地', max_length=64, blank=True, null=True)
    price = models.FloatField(verbose_name='成本单价', blank=True, null=True)
    # total_amount = models.FloatField(verbose_name='成本总价', blank=True, null=True)
    quantity = models.FloatField(verbose_name='库存数量', blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.goods.code

    class Meta:
        verbose_name = '商品库存'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class GoodsTransfer(models.Model):
    """库存调拨"""
    code = models.CharField(verbose_name='调拨单编号', max_length=24)
    transfer_time = models.DateField(verbose_name='调拨时间', blank=True, null=True)

    user = models.ForeignKey(to=UserInfo, verbose_name='调拨人', blank=True, null=True, on_delete=models.SET_NULL, db_constraint=False)
    out_house = models.ForeignKey(to=StoreHouse, verbose_name='调出仓库', blank=True, null=True, related_name='out_houses', on_delete=models.SET_NULL, db_constraint=False)
    in_house = models.ForeignKey(to=StoreHouse, verbose_name='调入仓库', blank=True, null=True, related_name='in_houses', on_delete=models.SET_NULL, db_constraint=False)
    total_amount = models.FloatField(verbose_name='调拨金额', blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    oper_user = models.ForeignKey(to=UserInfo, verbose_name='操作员', related_name="oper_users", blank=True, null=True,
                                  on_delete=models.SET_NULL, db_constraint=False)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.code

    class Meta:
        verbose_name = '库存调拨'
        verbose_name_plural = verbose_name

    @classmethod
    def get_max_code(cls):
        date = datetime.datetime.now().strftime('%Y%m%d')

        date = "KCDB{}".format(date)

        max_code = cls.objects.filter(code__startswith=date).aggregate(max_code=Max("code"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(date, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(date, num)
            return code

    def save(self, *args, **kwargs):
        # 编号
        if self.code == "" or self.code is None:
            self.code = self.__class__.get_max_code()
        else:
            if self.id is None:
                exists = self.__class__.objects.filter(code=self.code).exists()
                if exists:
                    self.code = self.__class__.get_max_code()

        return super().save(*args, **kwargs)


# 调拨明细
class GoodsTransferDetail(models.Model):
    """调拨明细"""
    goods = models.ForeignKey(to=Goods, on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    transfer = models.ForeignKey(to=GoodsTransfer, related_name="details", on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    batch_num = models.CharField(verbose_name='批号', max_length=16, blank=True, null=True)
    nums = models.FloatField(verbose_name='调拨数量', blank=True, null=True)
    price = models.FloatField(verbose_name='单价', blank=True, null=True)
    total_amount = models.FloatField(verbose_name='金额', blank=True, null=True)
    remark = models.CharField(verbose_name='备注', max_length=128, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.goods.code

    class Meta:
        verbose_name = '调拨明细'
        verbose_name_plural = verbose_name
